package com.csdj.x315springboot.service;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.listener.adapter.MessageListenerAdapter;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

@Service
public class RedisService extends MessageListenerAdapter {

    private Logger log = LoggerFactory.getLogger("redisser");
    @Resource
    private RedisTemplate objectRedisTemplate;

    public <T> T getObject(String key){
        Object o = objectRedisTemplate.opsForValue().get(key);
        if(o == null)return null;
        return (T)o;
    }

    public void set(String key,String value){
        objectRedisTemplate.opsForValue().set(key,value);
    }

    public void set(String key,String value,int second){
        objectRedisTemplate.opsForValue().set(key,value,second, TimeUnit.SECONDS);
    }


    @Override
    public void onMessage(Message message, byte[] pattern) {
        String topic = new String(message.getChannel());
        String msg = new String(message.getBody());
        //处理消息
        log.info("topic:{}  msg:{}",topic,msg);
    }
}
